package com.midea.mgc.mgcaigc.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Date;

@Component
public class SignUtil {

    @Value("${aigc.appKey}")
    private String appKey;

    @Value("${aigc.secretKey}")
    private String secretKey;

    public String getSign(Long time) throws Exception {
        String ENCRYPT = "appKey=%s&currentTime=%s&secretKey=%s";
        //毫秒级时间戳，（这里time与请求体的currentTime保持一致）
//        Long time = new Date().getTime();
        System.out.println(time);
        String encryptStr = String.format(ENCRYPT,appKey,time,secretKey);
        byte[] key = new BASE64Decoder().decodeBuffer(secretKey);
        Security.setProperty("crypto.policy","unlimited");
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding","BC");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
        byte[] aes256Str = cipher.doFinal(encryptStr.getBytes(StandardCharsets.UTF_8));

        String sign = Base64.encodeBase64String(DigestUtils.md5Digest(aes256Str));
        System.out.println(sign);
        return sign;
    }
}
